from .celery import app
from .models import Chapter as ChapterModel, Novel as NovelModel, Book
from .models import Torrent
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)


@app.task
def save_novel(item):
    logger.info('save novel %s', item.get('title'))
    novel = NovelModel.get_or_none(NovelModel.id == item.get('id'))
    if novel:
        novel.__data__.update(dict(item))
        novel.save()
    else:
        NovelModel.create(**dict(item))


@app.task
def save_chapter(item):
    chapter = ChapterModel.get_or_none(ChapterModel.book_id == item.get(
        'book_id'), ChapterModel.sort_no == item.get('sort_no'))
    if chapter:
        chapter.__data__.update(dict(item))
        chapter.save()
    else:
        ChapterModel.create(**dict(item))


@app.task
def add(x, y):
    return x + y


@app.task
def save_ebook(item):
    logger.info('save ebook %s', item.get('title'))
    novel = Book.get_or_none(Book.slug == item.get('slug'))
    if novel:
        novel.__data__.update(dict(item))
        novel.save()
    else:
        Book.create(**dict(item))


@app.task
def save_torrent(item):
    logger.info('save torrent %s', item.get('title'))
    novel = Torrent.get_or_none(Book.magnet_link== item.get('magnet_link'))
    if novel:
        novel.__data__.update(dict(item))
        novel.save()
    else:
        Torrent.create(**dict(item))
